<script lang="ts" setup>
import { ElMessage } from 'element-plus'
import qs from 'qs'
import { GetData, PatchListSort } from '@/api/modules/clientAdminAccount.ts'
import { GetOptionData as GetStoreOption } from '@/api/modules/store'
import { GetOptionData as GetOpenID } from '@/api/modules/subscriber'
import GetCacheData from '@/store/modules/NewPageCache'

const router = useRouter()

const cacheData = GetCacheData()
let PageNum = cacheData.GetCacheData('clientAdminAccount').currentPage
const loading = ref(false)
const total = ref(0) // 总数据数

const findFrom = reactive({
  ...(cacheData.GetCacheData('clientAdminAccount').fromData),
})

const dataList: any = ref([])

const OptionObj = reactive({
  StoreOption: [],
  OpenIDOption: [],
})

// 获取数据
function GetDataList(PageIndex: number = 1, PageSize: number = 10) {
  loading.value = true
  const params = {
    PageIndex,
    PageSize,
    ...(findFrom.Username && { Username: findFrom.Username }),
    ...(findFrom.Mobile && { Mobile: findFrom.Mobile }),
    ...(findFrom.RoleId !== '~' && { RoleId: findFrom.RoleId }),
    ...(findFrom.Realname && { Realname: findFrom.Realname }),
    ...(findFrom.Nickname && { Nickname: findFrom.Nickname }),
    ...(findFrom.IsExpired && { IsExpired: findFrom.IsExpired }),
    ...(findFrom.AccountState !== '~' && { AccountState: findFrom.AccountState }),
    ...(findFrom.StoreId !== '~' && { StoreId: findFrom.StoreId }),
    ...(findFrom.OpenId && { OpenId: findFrom.OpenId }),
  }
  GetData(params).then((res: any) => {
    if (res.succeeded) {
      dataList.value = res.data.items
      total.value = res.data.total
      loading.value = false
    }
    else {
      ElMessage.error('查询失败')
      loading.value = false
    }
  })
}

// 查询
function Inquire() {
  GetDataList(1, cacheData.GetCacheData('clientAdminAccount').currentSize)
  cacheData.SetCacheData('clientAdminAccount', PageNum, cacheData.GetCacheData('clientAdminAccount').currentSize, findFrom)
}

// 改变状态
function ChangeDataType(row: any) {
  const params = {
    accountState: row.accountState,
    id: row.id,
  }
  PatchListSort(params).then((res: any) => {
    if (res.succeeded) {
      ElMessage.success('操作成功')
    }
    else {
      ElMessage.error('修改失败')
      GetDataList(cacheData.GetCacheData('clientAdminAccount').currentPage, cacheData.GetCacheData('clientAdminAccount').currentSize)
    }
  })
}

// 添加
function AddEvent() {
  router.push({
    name: 'clientAdminAccountDetail',
  })
}

// 编辑
function Redact(message: any) {
  localStorage.setItem('currentPage', `${PageNum}`)
  router.push({
    name: 'clientAdminAccountDetail',
    query: {
      id: message.id,
    },
  })
}

// 页码
function handleSizeChange(val: number) {
  GetDataList(1, val)
  cacheData.SetCacheData('clientAdminAccount', PageNum, val)
}
function handleCurrentChange(val: number) {
  GetDataList(val, cacheData.GetCacheData('clientAdminAccount').currentSize)
  cacheData.SetCacheData('clientAdminAccount', val, cacheData.GetCacheData('clientAdminAccount').currentSize)
  PageNum = val
}

const nowPageNum = computed(() => {
  return cacheData.GetCacheData('clientAdminAccount').currentPage || 1
})

onMounted(async () => {
  try {
    await GetDataList(cacheData.GetCacheData('clientAdminAccount').currentPage, cacheData.GetCacheData('clientAdminAccount').currentSize)

    await GetStoreOption().then((res: any) => {
      if (res.succeeded) {
        OptionObj.StoreOption = res.data
      }
    })

    const parameter = qs.stringify({ PageIndex: 1, PageSize: 200000 })
    await GetOpenID(parameter).then((res: any) => {
      if (res.succeeded) {
        OptionObj.OpenIDOption = res.data.items
          .filter((item: any) => item.userNickName) // 过滤掉 userNickName 为空的项
          .map((item: any) => ({
            label: item.userNickName,
            value: item.scOpenId,
          }))
      }
    })
  }
  catch (error) {
    console.error('Error fetching data:', error)
  }
})
</script>

<template>
  <PageMain>
    <SearchBar :show-toggle="false">
      <div class="header">
        <el-form>
          <div class="from">
            <el-form-item label="登录用户名">
              <el-input v-model="findFrom.Username" placeholder="请输入登录用户名" clearable @keyup.enter="Inquire" />
            </el-form-item>
            <el-form-item label="手机号">
              <el-input v-model="findFrom.Mobile" placeholder="请输入手机号" clearable @keyup.enter="Inquire" />
            </el-form-item>
            <el-form-item label="角色">
              <el-select v-model="findFrom.RoleId" placeholder="请选择角色">
                <el-option label="全部" value="~" />
                <el-option label="管理员" :value="1" />
                <el-option label="运营" :value="2" />
                <el-option label="门店" :value="3" />
              </el-select>
            </el-form-item>
            <el-form-item label="姓名">
              <el-input v-model="findFrom.Realname" placeholder="请输入姓名" clearable @keyup.enter="Inquire" />
            </el-form-item>
            <el-form-item label="昵称（预留）">
              <el-input v-model="findFrom.Nickname" placeholder="请输入昵称" clearable @keyup.enter="Inquire" />
            </el-form-item>
            <el-form-item label="是否过期">
              <el-select v-model="findFrom.IsExpired" placeholder="请选择" clearable>
                <el-option label="是" :value="true" />
                <el-option label="否" :value="false" />
              </el-select>
            </el-form-item>
            <el-form-item label="状态">
              <el-select v-model="findFrom.AccountState" placeholder="请选择状态">
                <el-option label="全部" value="~" />
                <el-option label="正常" :value="1" />
                <el-option label="已停用" :value="2" />
              </el-select>
            </el-form-item>
            <el-form-item v-if="Number(findFrom.RoleId) === 3" label="门店">
              <el-select v-model="findFrom.StoreId" placeholder="请选择门店">
                <el-option label="全部" value="~" />
                <el-option v-for="item in (OptionObj.StoreOption as any)" :key="item.id" :label="item.storeName" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item v-if="Number(findFrom.RoleId) === 3" label="用户">
              <el-select-v2
                v-model="findFrom.OpenId"
                :options="OptionObj.OpenIDOption"
                placeholder="请选择用户"
                filterable
                clearable
              />
            </el-form-item>
          </div>
        </el-form>
        <div class="text-right">
          <el-button @click="Inquire">
            查询
          </el-button>
        </div>
      </div>
    </SearchBar>
    <ElDivider border-style="dashed" />
    <div class="mb-5 text-right">
      <el-button type="success" @click="AddEvent">
        添加
      </el-button>
    </div>
    <el-table v-loading="loading" :data="dataList" stripe style="width: 100%;" border>
      <el-table-column align="center" prop="id" label="id" width="200" />
      <el-table-column align="center" prop="username" label="登录用户名" width="180" />
      <el-table-column align="center" prop="pwd" label="登录密码" width="200" />
      <el-table-column align="center" prop="headimgurl" label="头像" width="100">
        <template #default="scope">
          <el-avatar shape="square" :size="60" :src="scope.row.headimgurl" />
        </template>
      </el-table-column>
      <el-table-column align="center" prop="mobile" label="手机号" width="200" />
      <el-table-column align="center" prop="roleId" label="身份" width="200">
        <template #default="scope">
          {{ scope.row.roleId === 1 ? '管理员' : scope.row.roleId === 2 ? '运营' : '未定义' }}
        </template>
      </el-table-column>
      <el-table-column align="center" prop="realname" label="姓名" width="200" />
      <el-table-column align="center" prop="nickname" label="昵称（预留）" width="200" />
      <el-table-column align="center" prop="expiredTime" label="过期时间" width="200" />
      <el-table-column align="center" prop="addTime" label="添加时间" width="200" />
      <el-table-column align="center" prop="enable" label="启用" width="120" fixed="right">
        <template #default="scope">
          <el-switch
            v-model="scope.row.accountState"
            :active-value="1"
            :inactive-value="2"
            @click="ChangeDataType(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" fixed="right" min-width="120">
        <template #default="scope">
          <div class="table-button">
            <el-button type="primary" :disabled="scope.row.isMatch" @click="Redact(scope.row)">
              编辑
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div style="height: 10px;" />
    <el-pagination
      :default-page-size="cacheData.GetCacheData('clientAdminAccount').currentSize"
      :page-sizes="[5, 10, 20, 50, 100]"
      layout="total, sizes, ->, prev, pager, next, jumper"
      :total="total"
      :default-current-page="nowPageNum"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </PageMain>
</template>

<style scoped>
.header {
  display: grid;
  grid-template-columns: 6fr 1fr;
  grid-gap: 20px;

  .from {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    grid-gap: 20px;

    .el-form-item {
      margin-bottom: 0;
    }
  }
}
</style>
